package com.wl.filter;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.enums.ErrorInfo;
import com.wl.util.Myproperties;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 字符编码过滤器
 *
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-06 20:02
 */
@WebFilter("*.action")
public class CharacterFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) {
        Factory.setOptions(getOptions());
        initFace();
    }

    public void initFace() {
        String osName = System.getProperty("os.name");
        Myproperties mp = Myproperties.getMyProperties();
        String appId;
        String sdkKey;
        FaceEngine faceEngine;
        if (osName.toLowerCase().startsWith("win")) {
            appId = mp.getProperty("appId.win");
            sdkKey = mp.getProperty("sdkKey.win");
            faceEngine = new FaceEngine(mp.getProperty("faceEnginePath.win"));
        } else {
            appId = mp.getProperty("appId.linux");
            sdkKey = mp.getProperty("sdkKey.linux");
            faceEngine = new FaceEngine(mp.getProperty("faceEnginePath.linux"));
        }
        //激活引擎
        int activeCode = faceEngine.activeOnline(appId, sdkKey);

        if (activeCode != ErrorInfo.MOK.getValue() && activeCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue()) {
            System.out.println("引擎激活失败");
        } else {
            System.out.println("引擎激活成功");
        }
    }

    private Config getOptions() {
        Myproperties myProperties = Myproperties.getMyProperties();
        //这里省略了一些不必要的配置，可参考文档的说明

        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = myProperties.getProperty("alipay.gateway");
        config.signType = "RSA2";

        config.appId = myProperties.getProperty("alipay.appId");

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = myProperties.getProperty("alipay.privateKey");

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = myProperties.getProperty("alipay.publicKey");
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = myProperties.getProperty("alipay.notifyUrl");

        return config;
    }
}
